#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import click
from flask.cli import FlaskGroup

from src.app import create_app
from src.app.extensions import db
from src.app.models.user import User


app = create_app(os.getenv('FLASK_ENV', 'default'))


@click.group(cls=FlaskGroup, create_app=lambda: app)
def cli():
    """Flask应用管理工具"""
    pass


@app.shell_context_processor
def make_shell_context():
    """为flask shell添加上下文"""
    return {
        'db': db,
        'User': User
    }


@cli.command('create-admin')
@click.option('--username', prompt=True, help='管理员用户名')
@click.option('--email', prompt=True, help='管理员邮箱')
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True, help='管理员密码')
def create_admin(username, email, password):
    """创建管理员用户"""
    from werkzeug.security import generate_password_hash
    
    admin = User(
        username=username,
        email=email,
        password=generate_password_hash(password),
        role='admin'
    )
    
    db.session.add(admin)
    db.session.commit()
    
    click.echo(f'管理员 {username} 创建成功!')


@cli.command('init-db')
def init_db():
    """初始化数据库"""
    db.create_all()
    click.echo('数据库初始化完成!')


if __name__ == '__main__':
    cli() 